package com.dhcc.sds.base.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.base.entity.CdcDoctypeEntity;
import com.dhcc.cdc.base.service.ICdcDoctypeService;
import com.dhcc.cdc.busi.dao.CdcEmrMapper;
import com.dhcc.cdc.busi.dao.CdcEpisodeMapper;
import com.dhcc.cdc.busi.dao.CdcEprMapper;
import com.dhcc.cdc.busi.dao.CdcSurgeryMapper;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.*;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.dao.DictionaryMapper;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.sds.util.DHCAI;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.framework.util.ObjectUtil;
import com.dhcc.core.framework.util.RedisUtil;
import com.dhcc.sds.base.cache.formitem.FormItemCache;
import com.dhcc.sds.base.cache.formitemdic.FormItemDicCache;
import com.dhcc.sds.base.cache.qcentity.QcEntityCache;
import com.dhcc.sds.base.dao.SdsFunctionMapper;
import com.dhcc.sds.base.dao.SdsQcformItemMapper;
import com.dhcc.sds.base.entity.*;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.ISdsQcincaseOperlogService;
import com.dhcc.sds.standard.dao.*;
import com.dhcc.sds.standard.entity.*;
import com.dhcc.sds.util.StrUtil;
import com.google.common.base.CharMatcher;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Description: 项目取值函数类
 * @author:sunyingjie
 * @date:2021年06月04日14:02:49
 * @Copyright: (c) DHCC All rights reserved.
 */
@Service("getValueSrvOld")
public class GetValueSrvOld {
    @Autowired
    private SdsFunctionMapper sdsFunctionMapper;
    @Autowired
    private SdsStandSourceFieldMapper sdsStandSourceFieldMapper;
    @Autowired
    private SdsStandDicMapper sdsStandDicMapper;
    @Autowired
    private SdsStandDicsubMapper sdsStandDicsubMapper;
    @Autowired
    private SdsQcformItemMapper sdsQcformItemMapper;
    @Autowired
    private SdsStandOrderMatchMapper sdsStandOrderMatchMapper;
    @Autowired
    private CdcEpisodeMapper cdcEpisodeMapper;
    @Autowired
    private CdcEmrMapper cdcEmrMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private CdcEprMapper cdcEprMapper;
    @Autowired
    private CdcSurgeryMapper cdcSurgeryMapper;
    @Autowired
    private ICdcStructurationService cdcStructurationService;
    @Autowired
    private ICdcStrucresultService cdcStrucresultService;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ICdcTransferService cdcTransferService;
    @Autowired
    private ICdcLocationService cdcLocationService;
    @Autowired
    private ICdcOrdexecService cdcOrdexecService;
    @Autowired
    private ICdcOrdmastService cdcOrdmastService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private ICdcDiagnosisService cdcDiagnosisService;
    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private ICdcOrigchapterService cdcOrigchapterService;
    @Autowired
    private ICdcDoctypeService cdcDoctypeService;
    @Autowired
    private ISdsQcincaseOperlogService sdsQcincaseOperlogService;
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Resource
    private SdsStandDataSourceMapper sdsStandDataSourceMapper;
    @Resource
    private SdsStandDicMatchParamMapper sdsStandDicMatchParamMapper;
    // 取值用redis缓存key关键词
    private static String redisKeyWords = "GetValue_";

    /**
     * 获取病人住院基本信息
     * 通过数据源和取值字段
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expBaseInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return "";
            // 查询数据源字段
            //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
            SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
            if (CommonUtil.isEmpty(sdsStandSourceEntity.getSourceCode())) {
                return resultStr;
            }

            switch (sdsStandSourceEntity.getSourceCode()) {
                case "OEDateT":
                    //到达本院急诊或者门诊日期时间
                    CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeMapper.selectById(episodeId);
                    if (!StringUtils.isEmpty(cdcEpisodeEntity)) {
                        //住院次数
                        Integer admNums = cdcEpisodeEntity.getAdmNums();
                        //患者主索引
                        String patientCode = cdcEpisodeEntity.getPatientCode();
                        if (!StringUtils.isEmpty(admNums) && (admNums > 1)) {
                            List<CdcEpisodeEntity> CdcEpisodeEntitys = cdcEpisodeMapper.selectByPatientCode(patientCode);
                            //就诊类型:E急诊
                            CdcDictionaryEntity admType1 = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "E");
                            //就诊类型:O门诊
                            CdcDictionaryEntity admType2 = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "O");
                            for (CdcEpisodeEntity cdcEpisodeEntity1 : CdcEpisodeEntitys) {
                                //就诊类型过滤(只需要门诊和急诊的)
                                if (Objects.equals(admType1.getId(), cdcEpisodeEntity1.getBusAdmTypeId()) || Objects.equals(admType2.getId(), cdcEpisodeEntity1.getBusAdmTypeId())) {
                                    Long h = com.dhcc.sds.util.DateUtil.getDateCompare(cdcEpisodeEntity.getAdmDate(), cdcEpisodeEntity1.getAdmDate(), "h");
                                    if (h < 24) {
                                        resultStr = DateUtil.format(cdcEpisodeEntity1.getAdmDate(), "yyyy-MM-dd HH:mm:ss");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    break;
                case "InDeptDate":
                    //入住某科室日期时间
                    if (!StringUtils.isEmpty(dataConfig.getLinkStandId())){
                        SdsStandDicEntity dicEntity = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
                        List<CdcTransferEntity> cdcTransferEntities = cdcTransferService.selectList(new EntityWrapper<CdcTransferEntity>()
                                .eq("episode_id", episodeId).eq("is_active", 1));
                        for (CdcTransferEntity cdcTransferEntity : cdcTransferEntities){
                            if (!StringUtils.isEmpty(cdcTransferEntity.getTranBedId())) {
                                //只检索转科记录
                                continue;
                            }
                            CdcLocationEntity locationEntity = cdcLocationService.selectById(cdcTransferEntity.getTranLocId());
                            if (!StringUtils.isEmpty(locationEntity)){
                                //入住CCU日期时间
                                if ("ICU".equals(dicEntity.getName())){
                                    if (locationEntity.getDescription().matches(".*ICU.*|.*监护.*|.*CCU.*")) {
                                        resultStr = DateUtil.format(cdcTransferEntity.getTranDate(), "yyyy-MM-dd HH:mm:ss");
                                        break;
                                    }
                                }
                            //配置其他科室
                            }
                        }
                    }
                    break;
                case "OutDeptDate":
                    //离开某科室日期时间
                    if (!StringUtils.isEmpty(dataConfig.getLinkStandId())){
                        SdsStandDicEntity dicEntity = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
                        List<CdcTransferEntity> cdcTransferEntities = cdcTransferService.selectList(new EntityWrapper<CdcTransferEntity>()
                                .eq("episode_id", episodeId).eq("is_active", 1));
                        for (CdcTransferEntity cdcTransferEntity : cdcTransferEntities){
                            if (!StringUtils.isEmpty(cdcTransferEntity.getTranBedId())) {
                                //只检索转科记录
                                continue;
                            }
                            CdcLocationEntity locationEntity = cdcLocationService.selectById(cdcTransferEntity.getTranLocId());
                            if (!StringUtils.isEmpty(locationEntity)){
                                //入住CCU日期时间
                                if ("ICU".equals(dicEntity.getName())){
                                    if (locationEntity.getDescription().matches(".*ICU.*|.*监护.*|.*CCU.*")) {
                                        resultStr = DateUtil.format(cdcTransferEntity.getFromDate(), "yyyy-MM-dd HH:mm:ss");
                                        break;
                                    }
                                }
                            //配置其他科室
                            }
                        }
                    }
                    break;
                case "InHosTrans":
                    //到院交通工具,默认私家车
                    resultStr = "私家车";
                    Wrapper<CdcOrdexecEntity> ordexecEntityWrapper = new EntityWrapper<>();
                    ordexecEntityWrapper.eq("episode_id", episodeId).eq("is_active", 1);
                    List<CdcOrdexecEntity> cdcOrdexecEntities = cdcOrdexecService.selectList(ordexecEntityWrapper);
                    for (CdcOrdexecEntity cdcOrdexecEntity : cdcOrdexecEntities) {
                        CdcOrdmastEntity ordmastEntity = cdcOrdmastService.selectById(cdcOrdexecEntity.getOrderMastId());
                        if (!StringUtils.isEmpty(ordmastEntity)) {
                            if (ordmastEntity.getDescription().contains("救护车")) {
                                resultStr = "救护车";
                                break;
                            }
                        }
                    }
                    List<Map<String, Object>> result = new ArrayList<>();
                    List<List<Map<String, Object>>> result2 = new ArrayList<>();
                    Map<String, Object> map = new HashMap<>();
                    map.put("InHosTrans", resultStr);
                    result.add(map);
                    result2.add(result);
                    resultStr = calcItemVal2(itemId, dataConfig, result2);
                    break;
                default:
                    // 通过就诊号获取患者就诊信息
                    Map<String, Object> episodeInfo = sdsFunctionMapper.getPatientInfo(episodeId);
                    // 获取对象值
                    resultStr = ObjectUtil.toString(episodeInfo.get(sdsStandSourceEntity.getSourceCode()));
                    if (CommonUtil.equals(resultStr, "男")) {
                        resultStr = "M";
                    } else if (CommonUtil.equals(resultStr, "女")) {
                        resultStr = "F";
                    }
                    //对科室处理，去掉短横线和括号
                    if (CommonUtil.equals(sdsStandSourceEntity.getSourceCode(), "admloc")) {
                        if (CommonUtil.contains(resultStr, "-")) {
                            resultStr = resultStr.split("-")[1];
                        }
                        resultStr = resultStr.replace("(", "");
                        resultStr = resultStr.replace(")", "");
                        resultStr = resultStr.replace("/", "");
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取病人费用信息
     * 通过数据源和取值字段(这里配的是费用类型)
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expFeeInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return "";
            // 查询数据源输出字段
            //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
            SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
            if (sdsStandSourceEntity == null) {
                return resultStr;
            }
            // 查询患者费用信息
            Map param = new HashMap<>();
            param.put("episodeId", episodeId);
            if (CommonUtil.isEmpty(sdsStandSourceEntity.getSourceCode())) {
                return resultStr;
            }
            Map<Object, Object> feeMap = sdsFunctionMapper.getFeeByType(param);
            if (CommonUtil.isEmpty(feeMap)) {
                return resultStr;
            }
            if (CommonUtil.isNotEmpty(feeMap.get(sdsStandSourceEntity.getSourceCode()))) {
                resultStr = feeMap.get(sdsStandSourceEntity.getSourceCode()).toString();
                //处理精度，小数点后两位
                DecimalFormat df = new DecimalFormat("0.00");
                String value = df.format(Float.parseFloat(resultStr));
                resultStr = value;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取病人诊断信息
     * 通过数据源和取值字段(这里配的是诊断类型)
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expDiagInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return "";
            // 查询配置诊断类型
            SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
            SdsStandDicEntity dicEntity = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
            //根据数据中心字典对照获取病案编目
            CdcDictionaryEntity diagSource = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "F");
            List<CdcDiagnosisEntity> diagnosisEntities = new ArrayList<>();
            //配有标准字典根据对照参数取值
            if (null != sdsStandSourceEntity && null != dicEntity){
                //根据标准字典配置的关键词取值
                List<String> list = this.handleDicMatchParam(dicEntity.getId(), 2);
                //排除sql
                String filterTxt = list.get(0);
                //同时满足sql
                String keywordAndTxt = list.get(1);
                //满足一个sql
                String keywordOrTxt = list.get(2);
                diagnosisEntities = cdcDiagnosisService.selectDiagInfoByParam(episodeId, diagSource.getId(), null, filterTxt, keywordAndTxt, keywordOrTxt);
            }
            //只配置数据源
            if (null != sdsStandSourceEntity && null == dicEntity){
                diagnosisEntities = cdcDiagnosisService.selectDiagInfo(episodeId, diagSource.getId(), null);
            }
            for (CdcDiagnosisEntity cdcDiagnosisEntity : diagnosisEntities){
                String icd10 = cdcDiagnosisEntity.getIcd10();
                if (Objects.equals(1, cdcDiagnosisEntity.getIsMain())) {
                    //主诊断
                    if (Objects.equals("M4DICD10", sdsStandSourceEntity.getSourceCode())) {
                        //主要诊断ICD-10四位亚目编码与名称
                        if (icd10.length() > 4) {
                            resultStr = icd10.substring(0, 5);
                        }
                        String lastChar = resultStr.substring(resultStr.length()-1);
                        if ("x".equals(lastChar)) {
                            resultStr = resultStr.substring(0,resultStr.length()-1);
                        }
                        lastChar = resultStr.substring(resultStr.length()-1);
                        if (".".equals(lastChar)) {
                            resultStr = resultStr.substring(0,resultStr.length()-1);
                        }
                    } else if (Objects.equals("M6DICD10", sdsStandSourceEntity.getSourceCode())) {
                        //主要诊断ICD-10六位临床扩展编码与名称
                        String substring = "";
                        if (icd10.length() >= 8) {
                            substring = icd10.substring(7, 8);
                        }
                        if (Objects.equals("x", substring) && icd10.length() >= 11) {
                            resultStr = icd10.substring(0, 11);
                        } else if (!Objects.equals("x", substring) && icd10.length() >= 7) {
                            resultStr = icd10.substring(0, 7);
                        }
                    }
                }
                if (!StringUtils.isEmpty(resultStr)) {
                    break;
                }
            }
            if (CommonUtil.isNotEmpty(resultStr)) {
                List<Map<String, Object>> result = new ArrayList<>();
                List<List<Map<String, Object>>> result2 = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put(sdsStandSourceEntity.getSourceCode(), resultStr);
                result.add(map);
                result2.add(result);
                resultStr = calcItemVal2(itemId, dataConfig, result2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 匹配值域字典并返回结果
     *
     * @return
     */
    private String matchItemDic(String itemVal, Long itemId) {
        String resultStr = "";
        // 获取值域字典
//        Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//        itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//        List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
        List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
        for (SdsQcfitemDicEntity dicEntity : itemDicList) {
            String dicCode = dicEntity.getCode();
            String dicDesc = dicEntity.getDesc();
            if (dicDesc.contains(":") || dicDesc.contains("：")) {
                // 区间范围
                dicDesc = dicDesc.replace("：", ":").replace(" ", "");
                dicDesc = dicDesc.split(":")[1];
                dicDesc = dicDesc.replace("至", "-");
            } else {
                String icdCode = "";
                int l = dicDesc.length();
                for (int i = 0; i < l; i++) {
                    char xcon = dicDesc.charAt(i);
                    if ("".equals(xcon) || xcon > 127) {
                        break;
                    }
                    icdCode = icdCode + xcon;
                }
                dicDesc = icdCode;
            }
            boolean flg = this.checkICDArea(itemVal, dicDesc);
            if (flg) {
                resultStr += dicCode + ",";
            }
        }
        if (resultStr.length() > 0) {
            resultStr = resultStr.substring(0, resultStr.length() - 1);
        }
        return resultStr;
    }

    /**
     * 验证ICD是否在区间内
     *
     * @return
     */
    public boolean checkICDArea(String icd, String icdArea) {
        boolean flg = false;
        if (CommonUtil.isEmpty(icd) || CommonUtil.isEmpty(icdArea)) {
            return false;
        }
        //定义operCode的字母和数字
        String a1 = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).retainFrom(icd);
        String s3 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(icd);
        Double l3 = Double.valueOf(s3);

        icdArea = icdArea.replace("，", ",");
        icdArea = icdArea.replace("、", ",");
        icdArea = icdArea.replace("——", "~");
        icdArea = icdArea.replace("-", "~");
        // 区间直接包含icd
        if (icdArea.contains(icd)) {
            flg = true;
        } else {
            // 只有一个区间
            if (icdArea.contains("~") && !icdArea.contains(",")) {
                String[] split = icdArea.split("~");
                //字母获取
                String a2 = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).retainFrom(split[0]);
                //数字获取
                String s1 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(split[0]);
                String s2 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(split[1]);
                //字母判断
                if (Objects.equals(a1, a2)) {
                    Double l1 = Double.valueOf(s1);
                    Double l2 = Double.valueOf(s2);
                    if (l1 <= l3 && l3 <= l2) {
                        flg = true;
                    } else if (s3.contains(s1) || s3.contains(s2)) {
                        flg = true;
                    }
                }
            } else if (icdArea.contains(",")) {
                // 有多个区间
                String[] split = icdArea.split(",");
                for (String s : split) {
                    if (s.contains("~")) {
                        String[] subSplit = s.split("~");
                        //字母获取
                        String a2 = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).retainFrom(subSplit[0]);
                        //数字获取
                        String s1 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(subSplit[0]);
                        String s2 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(subSplit[1]);
                        //字母判断
                        if (Objects.equals(a1, a2)) {
                            Double l1 = Double.valueOf(s1);
                            Double l2 = Double.valueOf(s2);
                            if (l1 <= l3 && l3 <= l2) {
                                flg = true;
                                break;
                            } else if (s3.contains(s1) || s3.contains(s2)) {
                                flg = true;
                                break;
                            }
                        }
                    } else {
                        //字母获取
                        String a2 = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).retainFrom(s);
                        //数字获取
                        String s1 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(s);
                        //字母判断
                        if (Objects.equals(a1, a2)) {
                            if (s3.contains(s1)) {
                                flg = true;
                                break;
                            }
                        }
                    }
                }
            } else {
                //字母获取
                String a2 = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).retainFrom(icdArea);
                //数字获取
                String s1 = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(icdArea);
                //字母判断
                if (Objects.equals(a1, a2)) {
                    if (s3.contains(s1)) {
                        flg = true;
                    }
                }
            }
        }
        return flg;
    }

    /**
     * 根据术语集/编目代码，获取病案首页信息
     * 通过数据源和取值字段(配的是编目代码)
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 编目代码对应的的值
     */
    public String expEprInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return resultStr;
            // 获取单病种编目代码（在数据源输出字段中配置代码参数）
            String eprCode = "";
            if (CommonUtil.isNotEmpty(dataConfig.getDsId())) {
                SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
                if (!StringUtils.isEmpty(sdsStandSourceEntity)) {
                    eprCode = sdsStandSourceEntity.getSourceCode();
                    // 获取病案首页信息
                    CdcEprEntity epr = new CdcEprEntity();
                    epr.setEpisodeId(episodeId);
                    epr.setCode(eprCode);
                    epr.setIsActive(1);
                    epr = cdcEprMapper.selectOne(epr);
                    if (!StringUtils.isEmpty(epr)) {
                        resultStr = epr.getValue();
                    }
                }
            }
            if (CommonUtil.isEmpty(resultStr)) {
                return resultStr;
            }
            // 获取项目信息
            SdsQcformItemEntity formItem = FormItemCache.me().getFormItemById(itemId);
            DictionaryEntity typeDic = dictionaryMapper.selectById(formItem.getBtType());
            String btType = typeDic.getDescription();

            if (formItem.getBtCode().equals("CM-0-1-5")) {
                if ("有".equals(resultStr) || "是".equals(resultStr)) {
                    resultStr = "y";
                } else {
                    resultStr = "n";
                }
            } else {
                // 字典类型，有值域字典
                if (btType.contains("字典")) {
                    // 获取值域字典
//                    Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//                    itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//                    List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
                    List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
                    // 如果有值域字典，返回值域选择项
                    if (itemDicList.size() > 0) {
                        // 按照项目输出字段值与值域关键字匹配
                        resultStr = this.matchStandDicByDesc(itemDicList, resultStr);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取病人电子病历信息
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public Object expEmrInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        List<CdcEmrEntity> emrList = new ArrayList<>();
        try {
            if (dataConfig == null) return emrList;
            Wrapper<CdcEmrEntity> emrWpr = new EntityWrapper<>();
            emrWpr.eq("episode_id", episodeId);
            // 查询标准项目
            if (CommonUtil.isNotEmpty(dataConfig.getLinkStandId())) {
                SdsStandDicEntity standDic = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
                emrWpr.eq("title", standDic.getName());
            }
            // 查询标准子项目
            /*if (CommonUtil.isNotEmpty(dataConfig.getLinkStandId())) {
                SdsStandDicsubEntity standDicSub = sdsStandDicsubMapper.selectById(dataConfig.getLinkStandSubId());
                emrWpr.eq("sub_title", standDicSub.getDicDesc());
            }*/
            emrList = cdcEmrMapper.selectList(emrWpr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return emrList;
    }

    public String expEmrInfo2(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        if (StringUtils.isEmpty(dataConfig)) {
            return resultStr;
        }
        if (!StringUtils.isEmpty(dataConfig.getLinkStandId())) {
            SdsStandDicEntity standDicEntity = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
            if (!StringUtils.isEmpty(standDicEntity)) {
                Map<String, Object> map = new HashMap<>();
                map.put("episodeId", episodeId);
                List<CdcStructurationEntity> structurationEntities = cdcStructurationService.list(map);
                //List<Map<String,String>> resEMR = new ArrayList<>();
                //利用set去重
                Set<String> resEMR = new HashSet<>();
                //存储语义分析后电子病历数据
                for (CdcStructurationEntity cdcStructurationEntity : structurationEntities) {
                    //过滤标准项
                    Long origchapterId = cdcStructurationEntity.getOrigchapterId();
                    CdcOrigchapterEntity cdcOrigchapterEntity = cdcOrigchapterService.selectById(origchapterId);
                    CdcDoctypeEntity cdcDoctypeEntity = cdcDoctypeService.selectById(cdcOrigchapterEntity.getDocTypeId());
                    //eg:国伟主任医师首次病程记录  首次病程
                    if (cdcDoctypeEntity.getDescription().contains(standDicEntity.getName())) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("structurationId", cdcStructurationEntity.getId());
                        List<CdcStrucresultEntity> strucresultEntities = cdcStrucresultService.list(map1);
                        for (CdcStrucresultEntity cdcStrucresultEntity : strucresultEntities) {
                            String result = cdcStrucresultEntity.getResult();
                            JSONArray jsonArray = JSONArray.parseArray(result);
                            if (jsonArray.size() > 0) {
                                for (int i = 0; i < jsonArray.size(); i++) {
                                    com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String formal = (String) jsonObject.get("formal");
                                    String type = (String) jsonObject.get("type");
                                    resEMR.add(type + ":" + formal);
                                }
                            }
                        }
                    }

                }

                //存储语义分析后值域字典数据
//                Map<String, Object> map2 = new HashMap<>();
//                map2.put("formItemId", itemId);
//                List<SdsQcfitemDicEntity> list1 = sdsQcfitemDicMapper.list(map2);
                List<SdsQcfitemDicEntity> list1 = FormItemDicCache.me().getFormItemDicList(itemId);
                String dicStr = "";
                //对值域字典数据进行标记
                //Map<String, Map<Integer, Integer>> dicMap = new HashMap<>();
                Map<String, String> dicMap = new HashMap<>();
                int r = 0;
                for (SdsQcfitemDicEntity sdsQcfitemDicEntity : list1) {
                    if (Objects.equals("请选择", sdsQcfitemDicEntity.getDesc())) {
                        continue;
                    }
                    //Map<Integer, Integer> map1 = new HashMap<>();
                    String indStr;
                    dicStr = dicStr + sdsQcfitemDicEntity.getCode() + ":" + sdsQcfitemDicEntity.getDesc() + ",";
                    char[] chars = dicStr.toCharArray();
                    //map1.put(r, chars.length-1);
                    indStr = r + "-" + (r + (chars.length - 1));
                    r = r + chars.length;
                    dicMap.put(indStr, sdsQcfitemDicEntity.getCode());
                }

                //对字典内容进行语义分析
                String path = "";
                JSONArray parse = new JSONArray();
                String sdAnalysisServer = CdcConfigCache.me().getValueByKey("SDS", "SDAnalysisServer");
                if (!StringUtils.isEmpty(sdAnalysisServer)) {
                    path = sdAnalysisServer;
                }
                if (!StringUtils.isEmpty(path)) {
                    parse = DHCAI.parse(path, dicStr, "", "");
                }
                //JSONArray parse = DHCAI.parse("http://10.1.20.118:1223/tag", dicStr, "", "");
                //List<Map<String,String>> resDicIdx = new ArrayList<>();
                Map<String, String> dicRes = new HashMap<>();
                Set<String> resDic = new HashSet<>();
                for (int i = 0; i < parse.size(); i++) {
                    com.alibaba.fastjson.JSONObject jsonObject = parse.getJSONObject(i);
                    String name = (String) jsonObject.get("name");
                    String formal = (String) jsonObject.get("formal");
                    String type = (String) jsonObject.get("type");
                    String disease = (String) jsonObject.get("disease");
                    //String index = (String) jsonObject.get("index");
                    com.alibaba.fastjson.JSONArray jsonArray = (JSONArray) jsonObject.get("index");
                    //JSONArray jsonArray = JSONArray.parseArray(index);
                    JSONArray jsonArray1 = jsonArray.getJSONArray(0);
                    String startIdx = jsonArray1.get(0).toString();
                    //formal = formal + "," + startIdx;
                    //dicRes.put(type,formal);
                    resDic.add(type + ":" + formal);
                    dicRes.put(type + ":" + formal, startIdx);
                }


                //将值域字典的语义核心词与病历语义核心词进行匹配
                a:
                for (String str1 : resDic) {
                    for (String str2 : resEMR) {
                        if (Objects.equals(str1, str2)) {
                            //如果匹配，找到选项并返回
                            String s = dicRes.get(str1);
                            for (HashMap.Entry<String, String> entry : dicMap.entrySet()) {
                                String key = entry.getKey();
                                Boolean aBoolean = StrUtil.valueInRange(key, s);
                                //单选
                                if (aBoolean) {
                                    resultStr = dicMap.get(key);
                                    break a;
                                }
                            }

                        }
                    }
                }
            }
        }
        return resultStr;
    }

    /**
     * 通过关联标准项，获取患者医嘱信息
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expOrderInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            // 查询数据源配置信息
            if (dataConfig == null) return resultStr;
            // 采集时机, 获取取值条件
            String sqlStr = this.calcGetTiming(episodeId, dataConfig);

            List<List<Map<String, Object>>> result = new ArrayList<>();

            // 如果只配置标准项
            if (CommonUtil.isNotEmpty(dataConfig.getLinkStandId())) {
                Map param = new HashMap();
                // 查询标准项所有关联医嘱
                param.put("dicId", dataConfig.getLinkStandId());
                List<Long> ordMastList = new ArrayList<>();
                ordMastList = sdsFunctionMapper.getOrdMast(param);
                if (ordMastList.isEmpty()) {
                    //标准项未配置对照医嘱，取标准子项配置
                    ordMastList = sdsFunctionMapper.getOrdMastByDicId(dataConfig.getLinkStandId());
                }
                List<Map<String, Object>> list = sdsFunctionMapper.selectOrdExec(episodeId, null, ordMastList, sqlStr);
                if (!list.isEmpty()) {
                    result.add(list);
                }
                resultStr = calcItemVal2(itemId, dataConfig, result);
            } else {
                // 走自动匹配值域字典与项目标准字典取值
                List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
                Map<String, List<Map<String, Object>>> standResMap = new HashMap<>();
                for (SdsQcfitemDicEntity itemDic : itemDicList) {
                    SdsStandDicEntity standDic = new SdsStandDicEntity();
                    standDic.setName(itemDic.getDesc());
                    standDic.setParentId(dataConfig.getDsId());
                    standDic = sdsStandDicMapper.selectOne(standDic);
                    if (standDic != null) {
                        Map param = new HashMap();
                        // 查询标准项所有关联医嘱
                        param.put("dicId", standDic.getId());
                        List<Long> ordMastList;
                        ordMastList = sdsFunctionMapper.getOrdMast(param);
                        if (ordMastList.isEmpty()) {
                            //标准项未配置对照医嘱，取标准子项配置
                            ordMastList = sdsFunctionMapper.getOrdMastByDicId(standDic.getId());
                        }
                        List<Map<String, Object>> list = sdsFunctionMapper.selectOrdExec(episodeId, null, ordMastList, sqlStr);
                        if (!list.isEmpty()) {
                            standResMap.put(itemDic.getDesc(), list);
                        }
                    }
                }
                resultStr = calcItemVal(itemId, dataConfig, standResMap);
            }

            // 计算项目结果
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 通过标准项关联的医嘱项，查询已执行医嘱项
     *
     * @param episodeId
     * @param ordMthWpr
     */
    private List<Map<String, Object>> filterOrdExec(Long episodeId, Wrapper<SdsStandOrderMatchEntity> ordMthWpr, String sqlStr) {
        List<Map<String, Object>> orderList = new ArrayList<>();
        List<SdsStandOrderMatchEntity> orderMatchList = sdsStandOrderMatchMapper.selectList(ordMthWpr);
        for (SdsStandOrderMatchEntity orderMatch : orderMatchList) {
            // 查询患者医嘱信息
            Map param = new HashMap<>();
            param.put("episodeId", episodeId);
            param.put("ordMastId", orderMatch.getOrdmastId());
            param.put("sqlStr", sqlStr);
            List<Map<String, Object>> ordExecList = sdsFunctionMapper.getOrdExecList(param);
            if (CommonUtil.isEmpty(ordExecList)) {
                continue;
            }
            orderList.addAll(ordExecList);
        }

        return orderList;
    }

    /**
     * 通过关联标准项，获取患者检查信息
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expExamInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) {
                return resultStr;
            }
            // 采集时机, 获取取值条件
            String sqlStr = this.calcGetTiming(episodeId, dataConfig);
            List<List<Map<String, Object>>> result = new ArrayList<>();

            Map<String, List<Map<String, Object>>> tmpMap = new HashMap<>();
                // 如果标准项不为空
            if (CommonUtil.isNotEmpty(dataConfig.getLinkStandId())) {
                Map param = new HashMap();
                // 查询标准项所有关联医嘱
                param.put("dicId", dataConfig.getLinkStandId());
                List<Long> ordMastList = sdsFunctionMapper.getRisLinkOrdMthId(param);
                List<Map<String, Object>> list = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList, sqlStr);
                if (!list.isEmpty()) {
                    result.add(list);
                }
            } else { // 未配置标准项，查询患者所有检查项目
                List<Map<String, Object>> list = sdsFunctionMapper.selectExaminate(episodeId, null, new ArrayList<>(), sqlStr);
                result.add(list);
            }
            // 计算项目结果
            resultStr = calcItemVal2(itemId, dataConfig, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 通过关联检查项目，查询检查项结果
     *
     * @param episodeId
     * @param ordMastList
     * @param risMatchList
     * @param sqlStr
     */
    /*private List<Map<String, Object>> filterExamResult(Long episodeId, List<Long> ordMastList, List<Long> risMatchList, String sqlStr) {
        // 查询检查结果
        Map param = new HashMap<>();
        param.put("episodeId", episodeId);
        param.put("ordMastList", ordMastList);
        param.put("risMatchList", risMatchList);
        param.put("sqlStr", sqlStr);
        return sdsFunctionMapper.getExamResultList(param);
    }*/

    /**
     * 通过关联标准项，获取患者检验信息
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expLabInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return resultStr;
            // 采集时机, 获取取值条件
            String sqlStr = this.calcGetTiming(episodeId, dataConfig);
            Map<String, List<Map<String, Object>>> tmpMap = new HashMap<>();
            List<List<Map<String, Object>>> result = new ArrayList<>();
            // 如果标准项不为空
            if (CommonUtil.isNotEmpty(dataConfig.getLinkStandId())) {
                Map param = new HashMap();
                // 查询标准项关联医嘱
                param.put("dicId", dataConfig.getLinkStandId());
                //检验医嘱id
                List<Long> laborderIds = sdsFunctionMapper.getLisLinkOrdMthId(param);
                //检验组套:查询标本送检记录id
                //List<Long> labVisitIds = cdcLabSetService.selectLabVisitIdByLabOrder(laborderIds);
                List<Map<String, Object>> list = sdsFunctionMapper.selectLabReport(episodeId, null, laborderIds, sqlStr);
                if (!list.isEmpty()) {
                    result.add(list);
                }
            }

            // 计算项目结果
            resultStr = calcItemVal2(itemId, dataConfig, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 通过关联检验项目，查询检验小项结果
     *
     * @param episodeId
     * @param ordMastList
     * @param lisMatchList
     * @param sqlStr
     * @return
     */
    /*private List<Map<String, Object>> filterLabResult(Long episodeId, List<Long> ordMastList, List<Long> lisMatchList, String sqlStr) {
        // 查询检验结果
        Map param = new HashMap<>();
        param.put("episodeId", episodeId);
        param.put("ordMastList", ordMastList);
        param.put("risMatchList", lisMatchList);
        param.put("sqlStr", sqlStr);
        return sdsFunctionMapper.getLabReportList(param);
    }*/

    /**
     * 通过关联标准项，获取患者生命体征
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public String expSignInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return resultStr;

            // 查询数据源输出字段
            SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
            if (sdsStandSourceEntity == null) {
                return resultStr;
            }
            Map param = new HashMap<>();
            param.put("episodeId", episodeId);
            if (CommonUtil.isEmpty(sdsStandSourceEntity.getSourceCode())) {
                return resultStr;
            }
            param.put("signCode", sdsStandSourceEntity.getSourceCode());
            resultStr = sdsFunctionMapper.getSignByCode(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取病人手麻信息
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @param entityId  病种id
     * @return 项目取值字段的值
     */
    public String expOperInfo(Long episodeId, Long itemId, Long entityId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        try {
            if (dataConfig == null) return resultStr;
            // 查询配置诊断类型
            SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
            SdsStandDicEntity dicEntity = sdsStandDicMapper.selectById(dataConfig.getLinkStandId());
            //根据数据中心字典对照获取病案编目
            CdcDictionaryEntity surgSource = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "F1");
            List<CdcSurgeryEntity> surgeryEntities = new ArrayList<>();
            //配有标准字典根据对照参数取值
            if (null != sdsStandSourceEntity && null != dicEntity){
                //根据标准字典配置的关键词取值
                List<String> list = this.handleDicMatchParam(dicEntity.getId(), 1);
                //排除sql
                String filterTxt = list.get(0);
                //同时满足sql
                String keywordAndTxt = list.get(1);
                //满足一个sql
                String keywordOrTxt = list.get(2);
                //查询病案编目手术信息
                surgeryEntities = cdcSurgeryMapper.selectSurgeryInfoByParam(episodeId, surgSource.getId(), null, filterTxt, keywordAndTxt, keywordOrTxt);
            }
            //只配置数据源
            if (null != sdsStandSourceEntity && null == dicEntity){
                surgeryEntities = cdcSurgeryMapper.selectSurgeryInfo(episodeId, surgSource.getId(), null);
            }

            if (surgeryEntities.size() > 0) {
                //获取编目手术 (第一手术默认为主手术)
                CdcSurgeryEntity cdcSurgeryEntity = surgeryEntities.get(0);
                String code = cdcSurgeryEntity.getCode();
                if (Objects.equals("M4OCM3", sdsStandSourceEntity.getSourceCode())) {
                    //主要手术操作栏中提取ICD-9-CM-3四位亚目编码与名称
                    if (code.length() > 4) {
                        resultStr = code.substring(0, 5);
                    }
                    String lastChar = resultStr.substring(resultStr.length()-1);
                    if ("x".equals(lastChar)) {
                        resultStr = resultStr.substring(0,resultStr.length()-1);
                    }
                    lastChar = resultStr.substring(resultStr.length()-1);
                    if (".".equals(lastChar)) {
                        resultStr = resultStr.substring(0,resultStr.length()-1);
                    }
                } else if (Objects.equals("M6OCM3", sdsStandSourceEntity.getSourceCode())) {
                    //主要手术操作栏中提取ICD-9-CM-3六位临床扩展编码与名称
                    String substring = "";
                    if (code.length() >= 8) {
                        substring = code.substring(7, 8);
                    }
                    if (Objects.equals("x", substring) && code.length() >= 11) {
                        resultStr = code.substring(0, 11);
                    } else if (code.length() >= 7) {
                        resultStr = code.substring(0, 7);
                    }
                } else {
                    if (CommonUtil.equals("startDate", sdsStandSourceEntity.getSourceCode())) {
                        resultStr = DateUtil.getTime(cdcSurgeryEntity.getStartDate());
                    } else if (CommonUtil.equals("endDate", sdsStandSourceEntity.getSourceCode())) {
                        resultStr = DateUtil.getTime(cdcSurgeryEntity.getEndDate());
                    } else if (CommonUtil.equals("LoseBlood", sdsStandSourceEntity.getSourceCode())){
                        resultStr = cdcSurgeryEntity.getBloodLose();
                    }
                }
            }

            if (CommonUtil.isNotEmpty(resultStr)) {
                List<Map<String, Object>> result = new ArrayList<>();
                List<List<Map<String, Object>>> result2 = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put(sdsStandSourceEntity.getSourceCode(), resultStr);
                result.add(map);
                result2.add(result);
                resultStr = calcItemVal2(itemId, dataConfig, result2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取病人护理记录
     *
     * @param episodeId 就诊号
     * @param itemId    项目id
     * @return 项目取值字段的值
     */
    public Object expNurInfo(Long episodeId, Long itemId, SdsDataConfigEntity dataConfig) {
        // TODO
        return null;
    }

    /**
     * 获取默认值
     *
     * @param itemId 项目id
     * @return 默认值
     */
    public String expDefaultVal(Long itemId) {
        String resultStr = "";
        // 获取值域字典
//        Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//        itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//        List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
        // 获取项目信息
        SdsQcformItemEntity formItem = FormItemCache.me().getFormItemById(itemId);
        DictionaryEntity typeDic = dictionaryMapper.selectById(formItem.getBtType());
        String btType = typeDic.getDescription();
        List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
        if (btType.contains("多选")) {
            for (SdsQcfitemDicEntity dicEntity : itemDicList) {
                if (CommonUtil.equals(dicEntity.getIsDefault(), 1)) {
                    resultStr += dicEntity.getCode() + ",";
                }
            }
        } else {
            for (SdsQcfitemDicEntity dicEntity : itemDicList) {
                if (CommonUtil.equals(dicEntity.getIsDefault(), 1)) {
                    resultStr = dicEntity.getCode();
                    break;
                }
            }
        }
        return resultStr;
    }

    /**
     * 从结果集中取得数据源输出字段的值
     *
     * @param itemId     项目id
     * @param dataConfig 数据源配置
     * @param dataMap    结果集
     * @return 项目值
     */
    private String calcItemVal(Long itemId, SdsDataConfigEntity dataConfig, Map<String, List<Map<String, Object>>> dataMap) {
        String resultStr = "";
        // 获取项目信息
        SdsQcformItemEntity formItem = FormItemCache.me().getFormItemById(itemId);
        DictionaryEntity typeDic = dictionaryMapper.selectById(formItem.getBtType());
        String btType = typeDic.getDescription();
        // 字典类型，有值域字典
        if (btType.contains("字典")) {
            // 获取值域字典
//            Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//            itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//            List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
            List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
            // 如果有值域字典，返回值域选择项
            if (itemDicList.size() > 0) {
                if (CommonUtil.isEmpty(dataConfig.getDsId())) {
                    // 如果没有配取值字段，匹配值域字典和标准项字典
                    resultStr = this.autoValByDic(itemDicList, dataMap, btType);
                } else {
                    // 获取数据源输出字段值
                    String objVal = this.getFieldVal(dataConfig, dataMap);
                    // 按照项目输出字段值与值域关键字匹配
                    resultStr = this.matchStandDicByDesc(itemDicList, objVal);
                }
            }
        } else {
            if (CommonUtil.isEmpty(dataConfig.getDsId())) {
                return "";
            } else {
                // 获取数据源输出字段值
                resultStr = this.getFieldVal(dataConfig, dataMap);
            }
        }
        if (CommonUtil.isNotEmpty(resultStr)) {
            redisUtil.set(GetValueSrvOld.redisKeyWords+formItem.getBtCode(), dataMap);
        }
        return resultStr;
    }

    /**
     * 从结果集中取得数据源输出字段的值
     *
     * @param dataConfig 数据源配置
     * @param tmpMap     结果集
     * @return 字段值
     */
    private String getFieldVal(SdsDataConfigEntity dataConfig, Map<String, List<Map<String, Object>>> tmpMap) {
        String objVal = "";
       // SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
        SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
        if (sdsStandSourceEntity == null) {
            return objVal;
        }
        String fieldCode = sdsStandSourceEntity.getSourceCode();
        //获取缓存中的值
        Boolean aBoolean = redisUtil.hasKey(redisKeyWords+dataConfig.getValueItemCode());
        if (aBoolean) {
            String s = redisUtil.get(redisKeyWords+dataConfig.getValueItemCode());
            tmpMap = (Map<String, List<Map<String, Object>>>) JSON.parse(s);
        }
        sLoop:
        for (String key : tmpMap.keySet()) {
            List<Map<String, Object>> subList = tmpMap.get(key);
            for (Map<String, Object> order : subList) {
                objVal = order.get(fieldCode).toString();
                break sLoop;
            }
        }
        return objVal;
    }

    /**
     * 通过值域关键字匹配取值数据
     *
     * @param dicEntityList 值域字典
     * @param objVal        取值字段结果
     */
    private String matchStandDicByDesc(List<SdsQcfitemDicEntity> dicEntityList, String objVal) {
        String resultStr = "";
        /*if (CommonUtil.isEmpty(objVal)) {
            return resultStr;
        }
        // 遍历值域字典，通过描述查找关键字配置信息
        for (SdsQcfitemDicEntity dicEntity : dicEntityList) {
            String dicDesc = dicEntity.getDesc();
            if ("其他".equals(dicDesc) && "其他".equals(objVal)) {
                resultStr = dicEntity.getCode() + ",";
                break;
            }
            // 查询关键字信息
            Map keyMap = sdsFunctionMapper.getMatchKey(dicDesc);
            // 如果没有常用短语关键词配置，直接匹配描述
            if (CommonUtil.isEmpty(keyMap)) {
                if (objVal.contains(dicDesc) || dicDesc.contains(objVal)) {
                    resultStr += dicEntity.getCode() + ",";
                } else if(CommonUtil.isNotEmpty(dicEntity.getKeyword())) { // 值域字典里维护的关键词
                    if (objVal.contains(dicEntity.getKeyword())||dicEntity.getKeyword().contains(objVal)) {
                        resultStr += dicEntity.getCode() + ",";
                    }
                }
            } else {
                // 匹配关键词
                if (checkKeyArea(objVal, keyMap)) {
                    resultStr += dicEntity.getCode() + ",";
                }
            }
        }
        if (!"".equals(resultStr)) {
            resultStr = resultStr.substring(0, resultStr.length() - 1);
        }*/
        return resultStr;
    }

    /**
     * 结果值匹配关键词
     *
     * @param objVal 取值字段结果
     * @param keyMap 关键词集合
     */
    private Boolean checkKeyArea(String objVal, Map keyMap) {
        boolean flg = false;
        String dicKeys = String.valueOf(keyMap.get("dicKeys"));
        String dicFilters = String.valueOf(keyMap.get("dicFilters"));
        dicKeys.replace("，", ",").replace("、", ",");
        dicFilters.replace("，", ",").replace("、", ",");
        String[] keyArr = dicKeys.split(",");
        String[] filterArr = dicFilters.split(",");
        for (String f : filterArr) {
            if (!StringUtils.isEmpty(f)) {
                if (objVal.contains(f)) {
                    return false;
                }
            }
        }
        for (String k : keyArr) {
            if (!StringUtils.isEmpty(k)) {
                if (!objVal.contains(k)) {
                    continue;
                }
                flg = true;
            }
        }
        return flg;
    }

    /**
     * 通过值域字典匹配标准字典
     *
     * @param dicEntityList 值域字典
     * @param dataMap       通过标准项取到的数据集合
     * @param itemType      项目类型
     */
    private String autoValByDic(List<SdsQcfitemDicEntity> dicEntityList, Map<String, List<Map<String, Object>>> dataMap, String itemType) {
        String resultStr = "";
        Map<String, Object> tmpDicMap = new HashMap<>();
        loop:
        for (SdsQcfitemDicEntity dicEntity : dicEntityList) {
            // 如果值域为是否，只需要判断存在情况
            if (dicEntity.getDesc().contains("是") || dicEntity.getDesc().contains("否")) {
                for (String key : dataMap.keySet()) {
                    if (dataMap.get(key).size() > 0) {
                        resultStr = "y";
                        break loop;
                    }
                }
            } else {
                for (String key : dataMap.keySet()) {
                    // 如果字典含有"+"连接两个标准项
                    if (dicEntity.getDesc().contains("＋") || dicEntity.getDesc().contains("+")) {
                        dicEntity.setDesc(dicEntity.getDesc().replace("＋", "+"));
                        boolean joinFlg = true;
                        for (String subDicStr : dicEntity.getDesc().split("\\+")) {
                            if (CommonUtil.isEmpty(tmpDicMap.get(subDicStr))) {
                                joinFlg = false;
                            }
                        }
                        if (joinFlg) {
                            resultStr = dicEntity.getCode();
                        }
                    } else {
                        //将值域项目与标准项匹配
                        if (CommonUtil.contains(dicEntity.getDesc(), key)) {
                            if (dataMap.get(key).size() > 0) {
                                resultStr += dicEntity.getCode() + ",";
                                tmpDicMap.put(dicEntity.getDesc(), dicEntity.getCode());
                            }
                        }

                    }
                }
            }
        }
        if (resultStr.contains(",")) {
            resultStr = resultStr.substring(0, resultStr.length() - 1);
            // 如果是单选，选择符合条件字典的任一个
            if (CommonUtil.isNotEmpty(resultStr) && !itemType.contains("多选")) {
                resultStr = resultStr.split(",")[0];
            }
        }
        return resultStr;
    }

    /**
     * 根据采集时机，动态生成取值sql
     *
     * @param episodeId  病例就诊号
     * @param dataConfig 采集时机
     */
    private String calcGetTiming(Long episodeId, SdsDataConfigEntity dataConfig) {
        String sqlStr = "";
        String filterSqlByDate = "AND oe.bus_order_priority_id <> ${priorityId} AND (oe.first_exec_date BETWEEN str_to_date('${sTime}','%Y-%m-%d %H:%i:%s') AND str_to_date('${eTime}', '%Y-%m-%d %H:%i:%s') OR oe.start_date BETWEEN str_to_date('${sTime}','%Y-%m-%d %H:%i:%s') AND str_to_date('${eTime}', '%Y-%m-%d %H:%i:%s'))";
        String filterSqlByAsc = "AND oe.bus_order_priority_id <> ${priorityId} ORDER BY IF(ISNULL(oe.first_exec_date),1,0) ${seqType}, oe.start_date ${seqType}";
        String filterSqlByDesc = "AND oe.bus_order_priority_id <> ${priorityId} ORDER BY IF(ISNULL(oe.last_exec_date),0,1) ${seqType}, oe.start_date ${seqType}";
        String filterSqlByPriority = "AND oe.bus_order_priority_id = ${priorityId} ORDER BY oe.start_date ${seqType}";
        String filterSqlByInstruc = "AND oe.bus_order_instruc_id = ${instrucId} ORDER BY oe.start_date ${seqType}";
        String seqType = "";
        Long priorityId = 0L;
        Long instrucId = 0L;
        Long tmpTime = 0L;
        String fTime = "";
        String tTime = "";

        // 如果没有配置采集时机，默认入院首次
        if (CommonUtil.isEmpty(dataConfig.getGetTiming())) {
            return "ORDER BY IF(ISNULL(oe.first_exec_date),1,0) asc, oe.start_date asc";
        }
        // 获取采集时间描述
        DictionaryEntity getTimingDic = dictionaryMapper.selectById(dataConfig.getGetTiming());
        String getType = getTimingDic.getCode();
        // 如果采集时机包含手术，则先取手术开始、结束时间
        if (getType.contains("Oper")) {
            Wrapper<CdcSurgeryEntity> operWpr = new EntityWrapper<>();
            operWpr.eq("episode_id", episodeId).eq("is_active", 1).orderBy("start_date");
            List<CdcSurgeryEntity> operList = cdcSurgeryMapper.selectList(operWpr);
            if (operList.size() == 0) {
                return "";
            }
            // 只取首次手术
            Date startDate = DateUtil.parse("1900-01-01 00:00:00");
            Date endDate = DateUtil.parse("1900-01-01 00:00:00");
            switch (getType) {
                case "BfOper":
                    for (CdcSurgeryEntity oper : operList) {
                        if (oper.getStartDate() != null || oper.getEndDate() != null) {
                            startDate = oper.getStartDate();
                            break;
                        }
                    }
                    // 术前，默认手术前0.5-1小时
                    tmpTime = startDate.getTime();
                    fTime = DateUtil.getTime(new Date(tmpTime - 3600 * 1000));
                    tTime = DateUtil.getTime(new Date(tmpTime - 1800 * 1000));
                    sqlStr = filterSqlByDate;
                    break;
                case "InOper":
                    for (CdcSurgeryEntity oper : operList) {
                        if (oper.getStartDate() != null && oper.getEndDate() != null) {
                            startDate = oper.getStartDate();
                            endDate = oper.getEndDate();
                            break;
                        }
                    }
                    // 术中
                    fTime = DateUtil.getTime(startDate);
                    tTime = DateUtil.getTime(endDate);
                    sqlStr = filterSqlByDate;
                    break;
                case "AfOper":
                    for (CdcSurgeryEntity oper : operList) {
                        if (oper.getStartDate() != null || oper.getEndDate() != null) {
                            endDate = oper.getEndDate();
                            break;
                        }
                    }
                    // 术后，默认手术后72小时
                    tmpTime = endDate.getTime();
                    fTime = DateUtil.getTime(endDate);
                    tTime = DateUtil.getTime(new Date(tmpTime + 3 * 24 * 3600 * 1000));
                    sqlStr = filterSqlByDate;
                    break;
                case "AllOper":
                    for (CdcSurgeryEntity oper : operList) {
                        if (oper.getStartDate() != null || oper.getEndDate() != null) {
                            startDate = oper.getStartDate();
                            endDate = oper.getEndDate();
                            break;
                        }
                    }
                    //围术期
                    tmpTime = startDate.getTime();
                    fTime = DateUtil.getTime(new Date(tmpTime - 3600 * 1000));
                    tmpTime = endDate.getTime();
                    tTime = DateUtil.getTime(new Date(tmpTime + 3 * 24 * 3600 * 1000));
                    sqlStr = filterSqlByDate;
                    break;
                case "WithOperRoom":
                    // 带手术室 bus_order_instruc:1
                    CdcDictionaryEntity cdcDictionaryEntity2 = cdcDictionaryService.queryByTypeCodeAndCode("OrdData", "bus_order_instruc", "1");
                    if (!StringUtils.isEmpty(cdcDictionaryEntity2)) {
                        instrucId = cdcDictionaryEntity2.getId();
                    }
                    seqType = "ASC";
                    sqlStr = filterSqlByInstruc;
                    break;
            }
        } else {
            // 获取就诊时间
            CdcEpisodeEntity admObj = cdcEpisodeMapper.selectById(episodeId);
            Date admDate = admObj.getAdmDate();
            Date dishDate = admObj.getDishDate();
            switch (getType) {
                case "Emergency":
                    // 急诊, 默认早于入院时间
                    tmpTime = admDate.getTime();
                    fTime = DateUtil.getTime(new Date(tmpTime - 24 * 3600 * 1000));
                    tTime = DateUtil.getTime(new Date(tmpTime));
                    sqlStr = filterSqlByDate;
                    break;
                case "LastInHosp":
                    // 住院末次
                    seqType = "DESC";
                    sqlStr = filterSqlByDesc;
                    break;
                case "EMR-Inhos24":
                    // 急诊/入院24小时
                    tmpTime = admDate.getTime();
                    fTime = DateUtil.getTime(admDate);
                    tTime = DateUtil.getTime(new Date(tmpTime + 24 * 3600 * 1000));
                    sqlStr = filterSqlByDate;
                    break;
                case "DishHosMedi":
                    // 出院带药 bus_order_priority:OUT
                    CdcDictionaryEntity cdcDictionaryEntity = cdcDictionaryService.queryByTypeCodeAndCode("OrdData", "bus_order_priority", "OUT");
                    if (!StringUtils.isEmpty(cdcDictionaryEntity)) {
                        priorityId = cdcDictionaryEntity.getId();
                    }
                    seqType = "ASC";
                    sqlStr = filterSqlByPriority;
                    break;
                case "LongOrder":
                    // 长期医嘱 bus_order_priority:S
                    CdcDictionaryEntity cdcDictionaryEntity1 = cdcDictionaryService.queryByTypeCodeAndCode("OrdData", "bus_order_priority", "S");
                    if (!StringUtils.isEmpty(cdcDictionaryEntity1)) {
                        priorityId = cdcDictionaryEntity1.getId();
                    }
                    seqType = "ASC";
                    sqlStr = filterSqlByPriority;
                    break;
                case "DurHosp":
                    // 住院期间 医嘱日期范围为住院期间
                    fTime = DateUtil.getTime(admDate);
                    tTime = DateUtil.getTime(dishDate);
                    sqlStr = filterSqlByDate;
                    break;
                default:
                    // 默认入院首次
                    seqType = "ASC";
                    sqlStr = filterSqlByAsc;
                    break;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sTime", fTime);
        map.put("eTime", tTime);
        map.put("seqType", seqType);
        map.put("priorityId", priorityId);
        map.put("instrucId", instrucId);
        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        sqlStr = strSubstitutor.replace(sqlStr);
        return sqlStr;
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("field", "oe.start_date");
        map.put("sTime", "2021-05-21 10:21:43");
        map.put("eTime", "2021-05-28 15:21:43");
        map.put("test2", "bbbb");
        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        String filterSqlByDate = "AND ${field} BETWEEN str_to_date('${sTime}','%Y-%m-%d %H:%i:%s') AND str_to_date('${eTime}', '%Y-%m-%d %H:%i:%s')";
        String context3 = strSubstitutor.replace(filterSqlByDate);
        System.out.println("context3: " + context3);
    }


    private String calcItemVal2(Long itemId, SdsDataConfigEntity dataConfig, List<List<Map<String, Object>>> result) {
        String resultStr = "";
        // 获取项目信息
        SdsQcformItemEntity formItem = FormItemCache.me().getFormItemById(itemId);
        DictionaryEntity typeDic = dictionaryMapper.selectById(formItem.getBtType());
        String btType = typeDic.getDescription();
        // 字典类型，有值域字典
        if (btType.contains("字典")) {
            // 获取值域字典
//            Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//            itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//            List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
            List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
            // 如果有值域字典，返回值域选择项
            if (itemDicList.size() > 0) {
                a:
                for (SdsQcfitemDicEntity sdsQcfitemDicEntity : itemDicList) {
                    // 如果值域为是否，只需要判断存在情况
                    if (sdsQcfitemDicEntity.getDesc().contains("是") || sdsQcfitemDicEntity.getDesc().contains("否")) {
                        if (result.size() > 0) {
                            resultStr = "y";
                            break a;
                        } else {
                            resultStr = "n";
                            break a;
                        }
                    }
                    //单选满足一个就跳出循环
                    if (!btType.contains("多选")) {
                        for (List<Map<String, Object>> list : result) {
                            for (Map<String, Object> map : list) {
                                if (!StringUtils.isEmpty(dataConfig.getDsId())) {
                                    //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
                                    SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
                                    String fieldCode = sdsStandSourceEntity.getSourceCode();
                                    if (CommonUtil.isNotEmpty(map.get(fieldCode))) {
                                        if (sdsQcfitemDicEntity.getDesc().contains(map.get(fieldCode).toString()) ||
                                                map.get(fieldCode).toString().contains(sdsQcfitemDicEntity.getDesc())) {
                                            if (Objects.equals(1, dataConfig.getBtIsCache())) {
                                                //缓存
                                                redisUtil.set(redisKeyWords + formItem.getBtCode(), map);
                                            }
                                            resultStr = sdsQcfitemDicEntity.getCode();
                                            break a;
                                        }
                                    }
                                } else {
                                    for (String key : map.keySet()) {
                                        if (Objects.equals(sdsQcfitemDicEntity.getDesc(), map.get(key))) {
                                            if (Objects.equals(1, dataConfig.getBtIsCache())) {
                                                //缓存
                                                redisUtil.set(redisKeyWords + formItem.getBtCode(), map);
                                            }
                                            resultStr = sdsQcfitemDicEntity.getCode();
                                            break a;
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        //多选
                        for (List<Map<String, Object>> list : result) {
                            for (Map<String, Object> map : list) {
                                if (!StringUtils.isEmpty(dataConfig.getDsId())) {
                                    //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
                                    SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
                                    String fieldCode = sdsStandSourceEntity.getSourceCode();
                                    //解决联用项字典的问题（阿司匹林，氯吡格雷->阿司匹林＋氯吡格雷）
                                    if (sdsQcfitemDicEntity.getDesc().contains("＋") || sdsQcfitemDicEntity.getDesc().contains("+")) {
                                        sdsQcfitemDicEntity.setDesc(sdsQcfitemDicEntity.getDesc().replace("＋", "+"));
                                        boolean joinFlg = true;
                                        for (String subDicStr : sdsQcfitemDicEntity.getDesc().split("\\+")) {
                                            if (StringUtils.isEmpty(redisUtil.get(redisKeyWords + formItem.getBtCode() + subDicStr))) {
                                                joinFlg = false;
                                            }
                                        }
                                        if (joinFlg) {
                                            resultStr += sdsQcfitemDicEntity.getCode() + ",";
                                            //break a;
                                        }

                                    }
                                    if (CommonUtil.isNotEmpty(map.get(fieldCode))) {
                                        if (sdsQcfitemDicEntity.getDesc().contains(map.get(fieldCode).toString()) ||
                                                map.get(fieldCode).toString().contains(sdsQcfitemDicEntity.getDesc())) {
                                            if (Objects.equals(1, dataConfig.getBtIsCache())) {
                                                //缓存
                                                redisUtil.set(redisKeyWords + formItem.getBtCode(), map);
                                            }
                                            resultStr += sdsQcfitemDicEntity.getCode() + ",";
                                        }
                                    }
                                } else {
                                    for (String key : map.keySet()) {
                                        if (Objects.equals(sdsQcfitemDicEntity.getDesc(), map.get(key))) {
                                            if (Objects.equals(1, dataConfig.getBtIsCache())) {
                                                //缓存
                                                redisUtil.set(redisKeyWords + formItem.getBtCode(), map);
                                            }
                                            resultStr += sdsQcfitemDicEntity.getCode() + ",";
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            } else {
                // 无值域字典
                if (StringUtils.isEmpty(dataConfig.getDsId())) {
                    return "";
                } else {
                    // 获取数据源输出字段值
                    resultStr = this.getFieldVal2(dataConfig, result);
                }
            }
        } else {
            // 无值域字典
            if (StringUtils.isEmpty(dataConfig.getDsId())) {
                return "";
            } else {
                // 获取数据源输出字段值
                resultStr = this.getFieldVal2(dataConfig, result);
            }
        }
        return resultStr;
    }

    private String getFieldVal2(SdsDataConfigEntity dataConfig, List<List<Map<String, Object>>> result) {
        String objVal = "";
        //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
        SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
        if (sdsStandSourceEntity == null) {
            return objVal;
        }
        String fieldCode = sdsStandSourceEntity.getSourceCode();
        //关联了取值项目
        if (!StringUtils.isEmpty(dataConfig.getValueItemCode())) {
            //获取缓存中的值
            Boolean aBoolean = redisUtil.hasKey(redisKeyWords+dataConfig.getValueItemCode());
            if (aBoolean) {
                String s = redisUtil.get(redisKeyWords+dataConfig.getValueItemCode());
                Map<String, Object> map = (Map<String, Object>) JSON.parse(s);
                objVal = map.get(fieldCode).toString();
                //获取后删除
                redisUtil.delete(redisKeyWords+dataConfig.getValueItemCode());
            }
        } else {
            for (List<Map<String, Object>> list : result) {
                for (Map<String, Object> map : list) {
                    objVal = map.get(fieldCode).toString();
                    if (!StringUtils.isEmpty(objVal)) {
                        break;
                    }
                }
            }
        }
        return objVal;
    }

    /**
     * 清除当前取值redis缓存数据
     */
    public void cleanRedis() {
        redisUtil.deleteByKeyWords(redisKeyWords);
    }

    public String vteInfo(Long episodeId, Long itemId, Long entityId, SdsDataConfigEntity dataConfig) {
        // 获取HIS就诊号
        CdcEpisodeEntity paadm = cdcEpisodeMapper.selectById(episodeId);
        String patientId = paadm.getXcode();
        String resultStr = "";
        if (dataConfig == null) return "";
        // 查询数据源字段
        SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
        if (CommonUtil.isEmpty(sdsStandSourceEntity.getSourceCode())) {
            return resultStr;
        }
        SdsQcentityEntity qcEntity = QcEntityCache.me().getQcEntityById(entityId);
        String abbrev = qcEntity.getAbbrev();
        if (CommonUtil.equals(abbrev, "AECOPD")) {
            String subUrl = "/api/getMZFitem?EpisodeID=";
            resultStr = this.getMZFitem(patientId, itemId, sdsStandSourceEntity.getSourceCode(),subUrl);
        } else if (CommonUtil.equals(abbrev, "DVT")) {
            String subUrl = "/api/getWSQitem?EpisodeID=";
            resultStr = this.getWSQAndZGWitem(patientId, itemId, sdsStandSourceEntity.getSourceCode(),subUrl);
        } else {
            String subUrl = "/api/getZGWYFVTEitem?EpisodeID=";
            resultStr = this.getWSQAndZGWitem(patientId, itemId, sdsStandSourceEntity.getSourceCode(),subUrl);
        }
        return resultStr;
    }

    private JSONObject vteHttpGet(String subUrl, String episodeId) {
        JSONObject obj = new JSONObject();
        // VTE服务url
        String vteServerUrl = CdcConfigCache.me().getValueByKey("SDS","VTEServer");
        // 创建httpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建请求方法的实例，并指定请求URL
        String url = vteServerUrl + subUrl + episodeId;
        HttpGet get = new HttpGet(url);
        // 调用execute,返回response
        CloseableHttpResponse response = null;
        try {
            response = client.execute(get);
            String str = EntityUtils.toString(response.getEntity());
            obj = JSONObject.parseObject(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 根据就诊号获取【慢阻肺】相关VTE结果
     *
     * @param episodeId
     * @return
     */
    private String getMZFitem(String episodeId, Long itemId, String fieldCode, String subUrl) {
        String result = "";
        JSONObject obj = this.vteHttpGet(subUrl, episodeId);
        int status = obj.getInteger("code");
        if (status == 200) {
            Object strObj = obj.getJSONObject("data").get(fieldCode);
            if (CommonUtil.equals(fieldCode, "isHighRisk")) {
                if ((int) strObj == 1) {
                    result = "y";
                } else {
                    result = "n";
                }
            } else if (CommonUtil.equals(fieldCode, "treatList")) {
                if (CommonUtil.isNotEmpty(strObj)) {
                    JSONArray array = JSONArray.parseArray(String.valueOf(strObj));
                    // 获取值域字典
//                    Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//                    itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//                    List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
                    List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
                    a:
                    for (SdsQcfitemDicEntity dic : itemDicList) {
                        for (int i = 0; i < array.size(); i++) {
                            /*if (CommonUtil.isNotEmpty(dic.getKeyword())) {
                                if (dic.getKeyword().equals(array.getString(i))) {
                                    result += dic.getCode() + ",";
                                    continue a;
                                }
                            } else {
                                if (dic.getDesc().contains(array.getString(i))) {
                                    result += dic.getCode() + ",";
                                    continue a;
                                }
                            }*/
                            if (dic.getDesc().contains(array.getString(i))) {
                                result += dic.getCode() + ",";
                                continue a;
                            }
                        }
                    }
                }
            } else if (CommonUtil.equals(fieldCode, "otherTreat")) {
                if (CommonUtil.isNotEmpty(strObj)) {
                    result = String.valueOf(strObj);
                }
            }
        }
        return result;
    }

    /**
     * 根据就诊号获取【围术期预深静脉血栓】相关VTE结果 或 【中高危风险患者预防静脉血栓】相关VTE结果
     *
     * @param episodeId
     * @return
     */
    private String getWSQAndZGWitem(String episodeId, Long itemId, String fieldCode, String subUrl) {
        String result = "";
        JSONObject obj = this.vteHttpGet(subUrl, episodeId);
        int status = obj.getInteger("code");
        if (status == 200) {
            Object strObj = obj.getJSONObject("data").get(fieldCode);
            if (CommonUtil.isNotEmpty(strObj)) {
                if (CommonUtil.equals(fieldCode, "score")) {
                    result = String.valueOf(strObj);
                } else {
                    // 获取值域字典
//                    Wrapper<SdsQcfitemDicEntity> itemDicWpr = new EntityWrapper<>();
//                    itemDicWpr.eq("form_item_id", itemId).eq("is_active", 1);
//                    List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.selectList(itemDicWpr);
                    List<SdsQcfitemDicEntity> itemDicList = FormItemDicCache.me().getFormItemDicList(itemId);
                    for (SdsQcfitemDicEntity dic : itemDicList) {
                       /* if (CommonUtil.isNotEmpty(dic.getKeyword())) {
                            if (dic.getKeyword().equals(strObj.toString())) {
                                result = dic.getCode();
                                break;
                            }
                        } else {
                            if (dic.getDesc().contains(strObj.toString())) {
                                result = dic.getCode();
                                break;
                            }
                        }*/
                        if (dic.getDesc().contains(strObj.toString())) {
                            result = dic.getCode();
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    //处理关键字，拼接成sql
    private List<String> handleDicMatchParam(Long dicEntityId, Integer type) {
        List<String> res = new ArrayList<>();

        //排除关键字sql
        String filterTxt = "";
        //同时满足sql
        String keywordAndTxt = "";
        //满足一个sql
        String keywordOrTxt = "";

        List<SdsStandDicMatchParamEntity> dicMatchParamEntities = sdsStandDicMatchParamMapper.selectList(new EntityWrapper<SdsStandDicMatchParamEntity>()
                .eq("dic_id", dicEntityId));
        for (SdsStandDicMatchParamEntity dicMatchParamEntity : dicMatchParamEntities){
            if ("O".equals(dicMatchParamEntity.getFilterType())){
                //O-排除 排除只处理对照内容只有一个的情况（包含&未考虑
                filterTxt = filterTxt + "|" + dicMatchParamEntity.getCompareContent();
            }else if ("I".equals(dicMatchParamEntity.getFilterType())){
                if (dicMatchParamEntity.getCompareContent().contains("&")){
                    String[] split1 = dicMatchParamEntity.getCompareContent().split("&");
                    if (1 == type){
                        //手术
                        for (int i = 0; i <= split1.length - 1; i++) {
                            if (i == 0) {
                                keywordAndTxt = keywordAndTxt + " or code like '%" + split1[0] + "%'";
                            } else {
                                keywordAndTxt = keywordAndTxt + " and code like '%" + split1[i] + "%'";
                            }
                        }
                    }else if (2 == type){
                        //诊断
                        for (int i = 0; i <= split1.length - 1; i++) {
                            if (i == 0) {
                                keywordAndTxt = keywordAndTxt + " or icd10 like '%" + split1[0] + "%'";
                            } else {
                                keywordAndTxt = keywordAndTxt + " and icd10 like '%" + split1[i] + "%'";
                            }
                        }
                    }
                }else {
                    keywordOrTxt = keywordOrTxt + "|" +dicMatchParamEntity.getCompareContent();
                }
            }
        }

        if ("" != filterTxt) {
            filterTxt = filterTxt.substring(1, filterTxt.length());
        }
        if ("" != keywordOrTxt) {
            keywordOrTxt = keywordOrTxt.substring(1, keywordOrTxt.length());
        }
        if ("" != keywordAndTxt && "" == keywordOrTxt) {
            keywordAndTxt = keywordAndTxt.replaceFirst("or", "and");
        }

        res.add(filterTxt);
        res.add(keywordAndTxt);
        res.add(keywordOrTxt);
        return res;
    }

    /**
     * 单病种入组信息
     * @param episodeId
     * @param itemId
     * @param entityId
     * @param dataConfig
     * @return
     */
    public String sdsIntheInfo(Long mrListId, Long episodeId, Long itemId, Long entityId, SdsDataConfigEntity dataConfig) {
        String resultStr = "";
        if (dataConfig == null) return "";
        // 查询数据源字段
        //SdsStandSourceFieldEntity sourceField = sdsStandSourceFieldMapper.selectById(dataConfig.getSourceField());
        SdsStandSourceEntity sdsStandSourceEntity = sdsStandDataSourceMapper.selectById(dataConfig.getDsId());
        if (CommonUtil.isEmpty(sdsStandSourceEntity.getSourceCode())) {
            return resultStr;
        }
        if ("intheReason".equals(sdsStandSourceEntity.getSourceCode())) {
            Wrapper<SdsQcincaseOperlogEntity> wpr = new EntityWrapper<>();
            wpr.eq("in_case_id", mrListId).eq("oper_state", "I");
            SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity = sdsQcincaseOperlogService.selectOne(wpr);
            String reasonStr  = sdsQcincaseOperlogEntity.getOperReason();
            String[] reasonArr = reasonStr.split(",");
            List<List<Map<String, Object>>> ressonList = new ArrayList<>();
            for (String ruleId : reasonArr) {
                SdsQcentityRuleEntity rule = sdsQcentityRuleService.selectById(ruleId);
                List<Map<String, Object>> result = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put("intheReason", rule.getRuleDesc());
                result.add(map);
                ressonList.add(result);
            }
            resultStr = calcItemVal2(itemId, dataConfig, ressonList);
        }

        return resultStr;
    }
}